﻿/******************************************************************
** auth: wei.huazhong
** date: 8/7/2020 10:47:24
** desc:
******************************************************************/

using System;
using System.Collections.Generic;
using static System.String;
using System.Text;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace Models
{
    public class ApiResult : ActionResult
    {

        [JsonProperty("code")]
        public int Code { get; set; }
        [JsonProperty("message")]
        public string Message { get; set; }
        [JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
        public dynamic Data { get; set; }

        public ApiResult()
        {
        }

        public ApiResult(int code)
        {
            Code = code;
        }

        public ApiResult(int code, string message) : this(code)
        {
            Message = message;
        }

        public ApiResult(int code, string message, dynamic data) : this(code, message)
        {
            Data = data;
        }

        /// <summary>
        /// 参考了ContentResult源码
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            ContentResult result = new ContentResult();
            result.Content = JsonConvert.SerializeObject(this);

            var executor = context.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<ContentResult>>();
            return executor.ExecuteAsync(context, result);
        }
    }
}
